package git.soulbgm.security.listener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static git.soulbgm.security.constant.SecurityConstants.*;

/**
 * 身份验证失败的监听器
 *
 * @author 贺瑞杰
 * @date 2021/01/07
 */
@Component
public class AuthenticationFailureListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {

    @Autowired
    private StringRedisTemplate redis;

    @Override
    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
        String username = event.getAuthentication().getPrincipal().toString();
        String loginLockKey = KEY_PREFIX_LOGIN_LOCK + username;
        String loginFailureKey = KEY_PREFIX_LOGIN_FAILURE + username;
        String flag = redis.opsForValue().get(loginLockKey);
        if (flag == null) {
            redis.opsForValue().increment(loginFailureKey, 1);
            redis.expire(loginFailureKey, LOGIN_FAILURE_COUNT_DURATION, TimeUnit.MINUTES);
        }
    }
}
